package com.gljx.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.CommonExport;
import com.gljx.util.TimeFormat;
import com.gljx.web.Entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.CustomLog;
import com.gljx.web.service.CustomLogService;


@Controller
@RequestMapping("/")
public class CustomLogController {

	@Autowired
	private CustomLogService customLogService;
	
	/**
	 * 查询日志
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryLog/look.action")
	public String selectCustomLog(HttpServletRequest request){
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        PageBean<CustomLog> pb = new PageBean<>();
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String time=format.format(date)+" 00:00:00";
		String beginTime = time;  
		String endTime = format.format(date)+" 23:59:59";
		try {
			//获取分页
            pb = getPageBean(request, beginTime, endTime, user.getFcompanyid());
            //获取分页数据
			List<CustomLog> customLogs = pb.getBeanList();
			//把数据传到页面
			request.setAttribute("customLogs", customLogs);
			request.setAttribute("pb", pb);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/customLog/logList";
	}
	
	/**
	 * 根据条件查询
	 * @param request
	 * @param fnameL2 功能名称
	 * @param fdescriptionL2 功能描述
	 * @param beginTime 开始时间
	 * @param endTime  结束时间
	 * @return 
	 */
	@RequestMapping("/queryLogByCondition")
    public String queryLogByCondition(HttpServletRequest request, String fnameL2, String fdescriptionL2, String beginTime, String endTime, String student) {
        PageBean<CustomLog> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
				//获取分页
            pb = getPageBean2(request, fnameL2.trim(), fdescriptionL2.trim(), beginTime, endTime, user.getFcompanyid(), student.trim());
            //获取分页数据
				List<CustomLog> customLogs = pb.getBeanList();
				//把数据传到页面
				request.setAttribute("customLogs", customLogs);
				request.setAttribute("pb", pb);
				request.setAttribute("fnameL2", fnameL2);
				request.setAttribute("fdescriptionL2", fdescriptionL2);
				request.setAttribute("beginTime", beginTime);
				request.setAttribute("endTime", endTime);
            request.setAttribute("student", student);
        } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
        return "/backHome/customLog/logList";
    }
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<CustomLog> getPageBean2(HttpServletRequest request, String fnameL2, String fdescriptionL2, String beginTime, String endTime, String companyId, String student) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fname_l2 as fnameL2,t.fdescription_l2 as fdescriptionL2,s.fname_l2 as studentName,");
		psql.append("to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,u.name as createName from ct_ds_customlog t left join ct_ds_student s ");
        psql.append("on t.cfstudentid=s.fid left join t_e_user u on t.fcreatorid=u.fid where 1=1 and t.FCONTROLUNITID = '" + companyId + "'");
        if("".equals(fnameL2)){
			
		}else{
			psql.append(" and t.fname_l2 like '%"+fnameL2+"%' ");
		}
		if("".equals(fdescriptionL2)){
			
		}else{
			psql.append(" and t.fdescription_l2 like '%"+fdescriptionL2+"%' ");
		}
        if ("".equals(student)) {

        } else {
            psql.append(" and s.fname_l2 like '%" + student + "%' ");
        }
        if ("".equals(beginTime) || "".equals(endTime)) {

        }else{
            psql.append(" and t.fcreatetime between to_date('" + beginTime + "','YYYY/MM/DD HH24:mi:ss')");
            psql.append(" and to_date('" + endTime + "','YYYY/MM/DD HH24:mi:ss')");
        }
        psql.append(" order by t.FCREATETIME desc");
        System.out.println(psql);
        int psize = 15; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= customLogService.selectPage(pindex, psql.toString(), psize);
		PageBean<CustomLog> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<CustomLog>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<CustomLog> getPageBean(HttpServletRequest request, String beginTime, String endTime, String companyId) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fname_l2 as fnameL2,t.fdescription_l2 as fdescriptionL2,s.fname_l2 as studentName,");
		psql.append("to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,u.name as createName from ct_ds_customlog t left join ct_ds_student s ");
        psql.append("on t.cfstudentid=s.fid left join t_e_user u on t.fcreatorid=u.fid where  t.FCONTROLUNITID = '" + companyId + "'");
        psql.append(" and t.fcreatetime between to_date('" + beginTime + "','YYYY/MM/DD HH24:mi:ss')");
        psql.append(" and to_date('" + endTime + "','YYYY/MM/DD HH24:mi:ss')");
        psql.append(" order by t.FCREATETIME desc");
        int psize = 15; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= customLogService.selectPage(pindex, psql.toString(), psize);
		PageBean<CustomLog> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<CustomLog>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=customLogService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param fnameL2        功能名称
     * @param fdescriptionL2 功能描述
     * @param beginTime      开始时间
     * @param endTime        结束时间
     */
    @RequestMapping("/importCustomLog")
    public void importCustomLog(HttpServletRequest request, HttpServletResponse response, String fnameL2,
                                String fdescriptionL2, String beginTime, String endTime, String student) {
        List<Object> data = new ArrayList<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //头部数据
        String head[] = {"功能名称", "功能描述", "创建时间", "创建人", "学生"};
        //长度
        Integer length[] = {5000, 10000, 5000, 3000, 3000};
        //查询数据
        List<CustomLog> customLogs = customLogService.selectCustomLogByInfo(user.getFcompanyid(), fnameL2.trim(), fdescriptionL2.trim(), beginTime, endTime, student);
        for (CustomLog customLog : customLogs) {
            data.add(customLog.getFnameL2());
            data.add(customLog.getFdescriptionL2());
            data.add(customLog.getFcreatetime());
            data.add(customLog.getCreateName());
            data.add(customLog.getStudentName());
        }
        try {
            //导出Excel
            CommonExport.importExcel(response, "日志" + TimeFormat.getNowTime2() + ".xls", "日志", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
